package com.nananren.common;

import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import com.nananren.exception.CustomerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理键重复异常
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result handleSqlException(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        String[] split = ex.getMessage().split(" ");
        String result = split[2] + "已存在";
        return Result.error(result);
    }

    @ExceptionHandler(MysqlDataTruncation.class)
    public Result handleMysqlDataTruncation(MysqlDataTruncation ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Data too long for column")) {
            return Result.error("输入的数据太长啦...");
        }
        return Result.error(ex.getMessage());
    }


    // 处理自定义业务异常
    @ExceptionHandler(CustomerException.class)
    public Result handleCustomerException(CustomerException ex) {
        log.error(ex.getMessage());
        return Result.error(ex.getMessage());
    }





    // 其他异常
//    @ExceptionHandler(Exception.class)
//    public Result handleException(Exception ex) {
//        log.info(ex.getMessage());
//        return Result.error("出错啦...")
//    }
}
